package com.ruoyi.flowable.listener;

import com.alibaba.druid.util.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.flowable.service.IActRejectRecordService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

/**
 * 驳回执行监听器
 */
@Slf4j
@Component("rejectExecutionListener")
public class RejectExecutionListener implements ExecutionListener {

    @Override
    public void notify(DelegateExecution execution) {
        log.info("=== 驳回执行监听器开始执行 ===");
        log.info("事件类型: {}", execution.getEventName());
        log.info("当前节点ID: {}", execution.getCurrentActivityId());
        log.info("流程实例ID: {}", execution.getProcessInstanceId());

        try {
            // 只有在节点开始时执行（避免重复执行）
            if ("start".equals(execution.getEventName())) {
                // 手动获取 Spring Bean
                IActRejectRecordService actRejectRecordService = SpringUtils.getBean(IActRejectRecordService.class);
                String activityId = execution.getCurrentActivityId();
                String processInstanceId = execution.getProcessInstanceId();
                String executionId = execution.getId();

                String rejectReason = getRejectReason(execution);

                // 在驳回记录表中添加记录
                // 注意：这里使用 executionId 作为任务ID，因为执行监听器没有具体的任务
                actRejectRecordService.addRejectRecord(processInstanceId, executionId, rejectReason);

                log.info("驳回记录添加成功，流程实例ID: {}, 节点: {}, 原因: {}",
                        processInstanceId, activityId, rejectReason);
            }
        } catch (Exception e) {
            log.error("添加驳回记录失败", e);
            // 不抛出异常，避免影响流程
        }
    }

    private String getRejectReason(DelegateExecution execution) {
        // 从流程变量中获取驳回原因
        String rejectReason = (String) execution.getVariable("rejectReason");
        if (StringUtils.isEmpty(rejectReason)) {
            rejectReason = (String) execution.getVariable("comment");
        }
        if (StringUtils.isEmpty(rejectReason)) {
            rejectReason = "系统自动驳回";
        }
        return rejectReason;
    }
}
